import trim from 'lodash/trim'
import isEmpty from 'lodash/isEmpty'
//替换所有
const replaceArray = (str, from, to) => {
  let obj = {},
    regex
  from.forEach(function (item, idx) {
    obj[item] = to[idx]
  })

  regex = new RegExp('(' + from.join('|') + ')', 'g')
  return str.replace(regex, function (match) {
    return obj[match]
  })
}

export const constantStr = (str = '', data = {}) => {
  // 1先提取出变量
  let _strArr = []
  try {
    let _fs = str.match(/#[^#]+#/gi)
    console.log('变量', _fs)
    if (_fs != null && _fs.length > 0) {
      _strArr = _fs
    }
  } catch (e) {
    console.log('先提取出公式变量出错：', e)
  }
  if (_strArr.length <= 0) {
    return str
  }
  // console.log('转换', _strArr, data)

  //2 提取变量对应的值
  let _values = []
  try {
    _strArr.forEach((item) => {
      _values.push(isEmpty(data[trim(item)]) ? '' : data[trim(item)])
    })
  } catch (e) {
    console.log('提取变量对应的值:', e)
  }
  // console.log('转换2', _strArr, _values)
  let conditionStr = replaceArray(str, _strArr, _values)
  console.log('conditionStr', conditionStr)
  return conditionStr === 'undefined' || conditionStr === 'null' ? '' : conditionStr
}
